const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    subject: [],
    time: 120 * 60 * 1000,
    timeData: {},
    point: true,
    op_in: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
    index: 0,
    //滑动坐标
    startX: 0,
    startY: 0,
    right: 0,
    error: 0,
    popup: false,
    checked: false,
    num: 0,
    radio: '',
    sum: 0,
    submit: false,
    exam_id: 0,
    exam_name:'',
    user_default:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let openId = wx.getStorageSync('openId')
 db.collection("user").doc(openId).get()
      .then(res => {

        this.setData({
          exam_id: Number(options.exam_id),
          exam_name:options.exam_name,
          user_default: res.data.user_default

        })
      })
    this.setData({
   
    })

    console.log(options)
    var exam_ids = Number(options.exam_id)
    wx.cloud.callFunction({
        // 云函数名称
        name: 'getexam',
        data: {
          exam_id: exam_ids,
        }
      })
      .then(res => {
        console.log('全部获取', res)
        this.setData({
          subject: res.result.data
        })
      })
      .catch(err => {
        console.log('全部获取失败', err)
      })
  },
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },

  // 开始考试
  start() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },
  //考试提示按钮事件
  confirm() {
    this.start();
  },
  cancel() {
    wx.navigateBack();
  },

  // 考试时间到处理函数
  finished() {
    Toast('倒计时结束');
  },



  //点击选项
  onChange(event) {
    let subject = this.data.subject
    let index = this.data.index

    this.setData({
      radio: event.detail,
      ['subject[' + index + '].user_answer[0]']: event.detail
    });
    console.log(event.target.id)


    if (event.detail == subject[index].answer) {

      var right = true
      var error = false
      var errors = Number(this.data.error) + 1
      let sum = this.data.sum
      // console.log(subject[index].score)
      sum = sum + subject[index].score,
        this.setData({
          error: errors,
          sum: sum,

          ['subject[' + index + '].error']: false,
          ['subject[' + index + '].right']: true
        })
      const _ = db.command
    let openId = wx.getStorageSync('openId')

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(5)
        }
      })
    } else {

      var rights = Number(this.data.right) + 1
      var error = true
      var right = false

      let sum = this.data.sum
      sum = sum - subject[index].score,
        this.setData({
          right: rights,
          sum: sum,
          ['subject[' + index + '].error']: true,
          ['subject[' + index + '].right']: false
        })
      const _ = db.command
    let openId = wx.getStorageSync('openId')

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(2)
        }
      })
    }
    // 点击选项后上传

  },


  // 双选部分
  onChanges(event) {
    let index = this.data.index
    this.setData({
      ['subject[' + index + '].user_answer']: event.detail,
    });
    let user_answer = this.data.subject[index].user_answer
    let answer = this.data.subject[index].answer
    console.log(user_answer)
    if (this.arrayEqual(user_answer, answer) == true) {

      // var right = true
      // var error = false
      var errors = Number(this.data.error) + 1
      this.setData({
        error: errors,
        ['subject[' + index + '].error']: false,
        ['subject[' + index + '].right']: true
      })
      const _ = db.command

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(5)
        }
      })
    } else {

      var rights = Number(this.data.right) + 1
      // var error = true
      // var right = false
      this.setData({
        right: rights,
        ['subject[' + index + '].error']: true,
        ['subject[' + index + '].right']: false
      })
      const _ = db.command
    let openId = wx.getStorageSync('openId')

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(2)
        }
      })
    }
  },
  arrayEqual: function (user_answer, answer) {
    //先将数组排序
    user_answer = user_answer.sort();
    answer = answer.sort();
    //判断数组长度是否相等，若不相等返回false
    if (user_answer.length != answer.length)
      return false;
    //逐个比较数组元素
    for (var i = 0; i < user_answer.length; ++i) {
      if (user_answer[i] !== answer[i])
        return false;
    }
    return true;
  },





  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},


  popop_d() {
    this.setData({
      popup: true
    })
  },



  // 点击答题卡关闭图标，关闭答题卡popup
  popup_close() {
    let popup = this.data.popup
    this.setData({
      popup: false
    })
  },
  model() {
    let model = this.data.model
    this.setData({
      model: false
    })
  },




  // 用户点击【收藏】，更新全题库信息。
  star(e) {
    console.log(e.target.id)
    let openId = wx.getStorageSync('openId')
    if (e.target.id.indexOf("+") == -1) {
      var _id = openId + '+' + e.target.id
    } else {
      var _id = e.target.id
    }
    let subject = this.data.subject
    let index = this.data.index
    this.setData({
      ['subject[' + index + '].star']: !subject[index].star,
    })
    console.log(_id)

    db.collection('subject-all').doc(_id).set({
      data: {
        star: subject[index].star,
        analysis: subject[index].analysis,
        answer: subject[index].answer,
        user_answer:subject[index].answer,
        chapters: subject[index].chapters,
        difficulty: subject[index].difficulty,
        option: subject[index].option,
        subject: subject[index].subject,
        title: subject[index].title,
        type: subject[index].type,
        right: subject[index].right,
        error: subject[index].error
      },
    })





  },

  //【切题处理】开始滑动---------------------------------------------------------------------
  touchstart: function (e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },

  // 【切题处理】滑动角度限制
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 / Math,atan()返回数据的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
  },
  //答题卡跳转
  open(e) {
    // console.log(e.target.id)
    this.setData({
      index: Number(e.target.id),
      popup: false
    })
  },

  //【切题处理】滑结束事件处理
  tochend(e) {
    let {
      startX,
      startY
    } = this.data;
    let slidingRange = 45; //
    let touchMoveX = e.changedTouches[0].clientX;
    let touchMoveY = e.changedTouches[0].clientY;
    let index = this.data.index
    let angle = this.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    });
    //为了方便计算取绝对值判断
    if (Math.abs(angle) > slidingRange && touchMoveY < startY) {
      // 向上滑动

    };
    if (Math.abs(angle) > slidingRange && touchMoveY > startY) {
      // 向下滑动

    };


    // 向右滑动事件，切换到上一题，第一题停止切换。
    if (Math.abs(angle) < 45 && touchMoveX > startX) {
      // 向右滑动
      if (index == 0) {
        this.setData({
          index: 0
        })
      } else {
        this.setData({
          index: index - 1
        })
      }
    };

    // 向左滑动屏幕事件，切换到下一题
    if (Math.abs(angle) < 45 && touchMoveX < startX) {
      // 向左滑动
      let length = this.data.subject.length
      let index = this.data.index
      // console.log(index)
      if ((index + 1) < length) {
        this.setData({
          index: index + 1,
        })
      } else {
        this.setData({
          index: index,
        })
      }


    }
  },


  jiaojuan() {
    let subject = this.data.subject
    var null_answer = 0
    for (let index = 0; index < subject.length; index++) {
      //  console.log(subject[index].user_answer)
      if (subject[index].user_answer == undefined) {
        null_answer++
      }

    }
    this.setData({
      submit: true,
      null_answer: null_answer
    })
  },
  arrayEqual: function (user_answer, answer) {
    //先将数组排序
     user_answer = user_answer.sort();
    answer = answer.sort();
    //判断数组长度是否相等，若不相等返回false
    if (user_answer.length != answer.length)
      return false;
    //逐个比较数组元素
    for (var i = 0; i < user_answer.length; ++i) {
      if (user_answer[i] !== answer[i])
        return false;
    }
    return true;
  },
  submit_confirm() {
    let subject = this.data.subject
    let sum = 0
  for (let index = 0; index < subject.length; index++) {

    if (subject[index].user_answer==undefined) {
      var   user_answer  =[]
    }else{
    var   user_answer = subject[index].user_answer

    }
    let answer = subject[index].answer
    if (this.arrayEqual(user_answer, answer) == true) {
      var errors = Number(this.data.error) + 1
      sum =sum+subject[index].score
      this.setData({
        error: errors,
        sum:sum,
        ['subject[' + index + '].error']: false,
        ['subject[' + index + '].right']: true
      })
      const _ = db.command
      let openId = wx.getStorageSync('openId')

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(5)
        }
      })
    } else {

      var rights = Number(this.data.right) + 1
      // var error = true
      // var right = false
      this.setData({
        right: rights,
        ['subject[' + index + '].error']: true,
        ['subject[' + index + '].right']: false
      })
      const _ = db.command
      let openId = wx.getStorageSync('openId')

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(2)
        }
      })
    }
    
  }

  let exam_id = this.data.exam_id
  let exam_name = this.data.exam_name
let user_default= this.data.user_default
  var newDateTime = Date.parse(new Date())
  var time = this.formatDate(newDateTime) //转换时间戳


  db.collection('user_exam_log').add({
    data: {
       subject :subject,
   exam_id:exam_id,
   exam_name :exam_name,
   sum:sum,
   time:time,
   user_default:user_default
    }
  })

  wx.redirectTo ({
    url: '/pages/function/exam_list/exam_list',
  })
  },
  
  

  // 时间戳转换函数
  formatDate: function (inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  },
})